package controllers

import (
	"errors"
	"youbei/dao"
	"youbei/utils/jobs"

	"github.com/beego/beego/toolbox"
	"github.com/gin-gonic/gin"
)

func GetCrontabList(c *gin.Context) {
	rep := map[string]interface{}{}
	crontabs := []dao.Crontab{}
	if total, err := GetRestul(c, "crontablist", &crontabs); err != nil {
		APIReturn(c, 500, "获取列表失败", err.Error())
		return
	} else {
		rep["count"] = total
	}

	rep["data"] = crontabs

	APIReturn(c, 200, "获取列表成功", &rep)
}

func GetCrontab(c *gin.Context) {
	crontab := dao.Crontab{}
	id := c.Param("id")
	if bol, err := dao.Localdb().ID(id).Get(&crontab); err != nil {
		APIReturn(c, 500, "获取数据失败", err)
		return
	} else {
		if !bol {
			APIReturn(c, 500, "获取数据为空", errors.New("获取数据为空"))
			return
		}
	}
	APIReturn(c, 200, "", crontab)
}

func AddCrontab(c *gin.Context) {
	ob := new(dao.Crontab)
	if err := c.Bind(ob); err != nil {
		APIReturn(c, 500, "解析数据失败:"+err.Error(), err)
		return
	}
	if ob.Pinlv == "day" {
		ob.Week = ""
		ob.Day = ""
	} else if ob.Pinlv == "week" {
		ob.Day = ""
	} else if ob.Pinlv == "month" {
		ob.Week = ""
	} else {
		APIReturn(c, 500, "执行频率错误", errors.New("执行频率错误"))
		return
	}
	if err := ob.Add(); err != nil {
		APIReturn(c, 500, "添加计划失败:"+err.Error(), err)
		return
	}
	toolbox.AddTask(ob.ID, toolbox.NewTask(ob.ID, ob.Crontab, jobs.Jobs(ob.ID)))
	APIReturn(c, 200, "成功", nil)
	return
}

func DeleteCrontab(c *gin.Context) {
	ob := new(dao.Crontab)
	ob.ID = c.Param("id")
	if err := ob.Delete(); err != nil {
		APIReturn(c, 500, "删除计划失败1", err.Error())
		return
	}
	if _, err := dao.Localdb().Where("cid=?", ob.ID).Delete(new(dao.TaskMountedCron)); err != nil {
		APIReturn(c, 500, "删除计划失败2", err.Error())
		return
	}
	toolbox.DeleteTask(ob.ID)
	APIReturn(c, 200, "删除计划成功", c.Param("id"))
}

func UpdateCrontab(c *gin.Context) {
	ob := new(dao.Crontab)
	ob.ID = c.Param("id")
	if err := c.Bind(ob); err != nil {
		APIReturn(c, 500, "解析数据失败", err.Error())
		return
	}
	if ob.Pinlv == "day" {
		ob.Week = ""
		ob.Day = ""
	} else if ob.Pinlv == "week" {
		ob.Day = ""
	} else if ob.Pinlv == "month" {
		ob.Week = ""
	} else {
		APIReturn(c, 500, "执行频率错误", errors.New("执行频率错误"))
		return
	}
	if err := ob.Update(); err != nil {
		APIReturn(c, 500, "修改计划失败", err)
		return
	}
	toolbox.AddTask(ob.ID, toolbox.NewTask(ob.ID, ob.Crontab, jobs.Jobs(ob.ID)))
	APIReturn(c, 200, "修改计划成功", c.Param("id"))
}
